package com.raymond.config.mybatis;

import com.raymond.entity.commons.BaseEnum;
import com.raymond.util.AssertUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

@MappedTypes(BaseEnum.class)
public class BaseEnumTypeHandler<E extends Enum<?> & BaseEnum> implements TypeHandler<E> {

    private Class<E> type;

    public BaseEnumTypeHandler(Class<E> type) {
        AssertUtil.notNull(type, "Type argument cannot be null!");
        this.type = type;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setNull(i, Types.INTEGER);
        } else {
            ps.setInt(i, parameter.getValue());
        }
    }

    @Override
    public E getResult(ResultSet rs, String columnName) throws SQLException {
        int code = rs.getInt(columnName);
        return rs.wasNull() ? null : BaseEnum.getEnumByValue(type, code);
    }

    @Override
    public E getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        int code = resultSet.getInt(columnIndex);
        return resultSet.wasNull() ? null : BaseEnum.getEnumByValue(type, code);
    }

    @Override
    public E getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        int code = callableStatement.getInt(columnIndex);
        return callableStatement.wasNull() ? null : BaseEnum.getEnumByValue(type, code);
    }
}
